package com.hms.common;

import java.io.Serializable;
import java.util.Date;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.springframework.stereotype.Component;

/**
 * 入库时自动填充创建、更新时间、操作人 <br>
 * 类详细说明.
 * <p>
 * Copyright: Copyright (c) 2013-4-13 下午4:08:08
 * <p>
 * Company: 北京宽连十方数字技术有限公司
 * <p>
 * 
 * @author wangpz@c-platform.com
 * @version 1.0.0
 */
@Component("entityInterceptor")
public class EntityInterceptor extends EmptyInterceptor {

	/** serialVersionUID */
	private static final long serialVersionUID = 1L;

	/**
	 * "创建日期"属性名称
	 */
	private static final String CREATE_DATE = "createDate";

	/**
	 * "修改日期"属性名称
	 */
	private static final String MODIFY_DATE = "modifyDate";

	/**
	 * 保存数据是调用该方法
	 */
	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		Date createDate = new Date();
		for (int i = 0; i < propertyNames.length; i++) {
			if (CREATE_DATE.equals(propertyNames[i]) || MODIFY_DATE.equals(propertyNames[i])) {
				state[i] = createDate;
			}
		}
		return true;
	}

	/**
	 * 更新数据时调用该方法
	 */
	@Override
	public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
		Date updateDate = new Date();
		for (int i = 0; i < propertyNames.length; i++) {
			if (MODIFY_DATE.equals(propertyNames[i])) {
				currentState[i] = updateDate;
			}
		}
		return true;
	}
}
